// ActionScript file
	
	import com.sodimac.util.alerts.alert;
	import com.sodimac.util.commons.DataGridExport;
	import com.sodimac.util.commons.EstadosBPM;
	import com.sodimac.util.commons.UploadPostHelper;
	import com.sodimac.util.commons.UtilString;
	import com.sodimac.v2s.events.grabarProductosPicEvent;
	import com.sodimac.v2s.model.ComprasModelLocator;
	import com.sodimac.v2s.view.components.ScreenFormat;
	import com.sodimac.v2s.vo.InfoSfpVO;
	
	import mx.binding.utils.ChangeWatcher;
	import mx.collections.ArrayCollection;
	import mx.controls.AdvancedDataGrid;
	import mx.controls.ComboBox;
	import mx.controls.List;
	import mx.controls.NumericStepper;
	import mx.controls.TextInput;
	import mx.events.AdvancedDataGridEvent;
    	
    
	/* datos de pantalla */        			
	[Bindable] public var problemaArr:ArrayCollection = new ArrayCollection();	
	[Bindable] public var problems:Array = new Array();
	[Bindable] public var infoSfpVo:InfoSfpVO = new InfoSfpVO();
	[Bindable] public var reporteURL: String;
	[Bindable] public var uploadDataURL: String;			
	
	[Bindable] public var pedidoCorpId: Number;
	[Bindable] public var empresaId: String;
	
	[Bindable] public var numericStepperFac:ClassFactory;
    [Bindable] public var numericStepperPrice:ClassFactory;
	[Bindable] public var comboFactory:ClassFactory;	
	[Bindable] public var screenFormat:ClassFactory;
	[Bindable] public var textInputFactory:ClassFactory;	
	[Bindable] public var myDropdownFactory:ClassFactory;
			
	
	/* datos modificados para envío */
	private var prodUpdated:ArrayCollection = new ArrayCollection();
	private var cwDataGrid:ChangeWatcher; 
	private var precioProblem:Number = 0;
	private var cantidadProblem:Number = 0;
	
	
	/* datos de nueva ventana */
	[Bindable] public var paisesArr:Array = new Array();
	[Bindable] public var paisesNacArr:Array = new Array();
	[Bindable] public var prodCorpData:ArrayCollection;	
	[Bindable] public var prodNacData:ArrayCollection;
//	[Bindable] public var infoSfpVo:InfoSfpVO;	
	[Bindable] public var paisesNombres:XMLList;
//	[Bindable] public var reporteURL: String;
//	[Bindable] public var uploadDataURL: String;
	[Bindable] public var existePedido: String = "0";				
		
//	[Bindable] public var pedidoCorpId: Number;
//	[Bindable] public var empresaId: String; 
	[Bindable] public var modelo: ComprasModelLocator = ComprasModelLocator.getInstance();
	
	
	[Bindable] public var prodNacCLData:ArrayCollection = new ArrayCollection();
	[Bindable] public var prodNacCOData:ArrayCollection = new ArrayCollection();
	[Bindable] public var prodNacPEData:ArrayCollection = new ArrayCollection();
	[Bindable] public var prodNacARData:ArrayCollection = new ArrayCollection();
	
	public var prodCorpUpdated:ArrayCollection = new ArrayCollection();
	public var prodNacUpdated:ArrayCollection = new ArrayCollection();
	public var paisesPartArray:Array = new Array("CL","CO","PE","AR");   //orden de los paises que pueden participar de una SFPC
//	public var paisesCorreccion:Array = new Array();                //contiene los paises a modificar
	public var cwDataGridNac:ChangeWatcher;	
	public var cwDataGridCorp:ChangeWatcher; 
	public var cwDataGridProbl:ChangeWatcher;
			
	
	/* fin datos nueva ventana */			
	
	
	private function onInit():void
	{
		trace("____"+  this.name + " -->  onInit.");
	
		//Escuchar cambios en arreglos 
		cwDataGridProbl = ChangeWatcher.watch(modelo,'problemasData',   onProblemsCharge)		
		cwDataGridCorp  = ChangeWatcher.watch(modelo,'prodConjHomData', onProductosChangeCorp);
		cwDataGridNac   = ChangeWatcher.watch(modelo,'prodConjNacData', onProductosChangeNac);
	
	}
	
	
				
  	private function onProblemsCharge(e:Event):void
	{
	    trace("____"+  this.name + " -->  onProblemsCharge.");

  		cwDataGridProbl.unwatch();	
		//set array problems
		if ( (problemaArr)  && (problemaArr.length > 0) ) 
		{
        	//problems = new Array();
        	for (var k:int = 0; k < problemaArr.length; k++)
	        {
	        	problems.push(problemaArr[k]["desc"]);
	        }
  			trace('Problems: ' +problems);
  			
			myDropdownFactory = new ClassFactory(List);
			myDropdownFactory.properties = {showDataTips:true, dataTipFunction:dataTipNombre}	  			
  			
			comboFactory = new ClassFactory(ComboBox);
			comboFactory.properties = {dataProvider:problems, dropdownFactory:myDropdownFactory};
 
  		}
  		
	    
	    
	}  	
	
	
  	private function onProductosChangeCorp(e:Event):void
	{
	    trace("____"+  this.name + " -->  onProductosChangeCorp.");
		 
		var col:AdvancedDataGridColumn;
        var cols:Array = dg_corp.columns;	
        
        cwDataGridCorp.unwatch();
		//ocultar pais
		if ((paisesArr)  && (paisesArr.length>0) )
		{
			//obtener pais
			var hidePaises:Array = new Array();
			hidePaises = new Array("CL","CO","PE","AR"); 
			for (var j:int=0;j<paisesArr.length;j++) 
			{
				var cod:String;
				cod = paisesArr[j];
				for (var k:int=0;k<paisesPartArray.length;k++)
				{
					if (paisesPartArray[k] == cod)
						hidePaises.splice(k,1);
				}
			} 
			trace("-------------------------");
			trace(hidePaises);
			for (j=0;j<hidePaises.length;j++) 
			{
				var name:String = UtilString.toLowerCase(hidePaises[j]);
 				for (k=0;k<cols.length;k++)  
				{
					 if (String(cols[k].dataField).indexOf(name +"_") != -1)
					 {
					 	 var column:FooterAdvancedDataGridColumn = dg_corp.columns[k];
					 	 column.visible = false;
					 }  
				} 
			}
			
		} else {
		
			//hide all 
			for (j=0;j<paisesPartArray.length;j++) 
			{
				var name2:String = UtilString.toLowerCase(paisesPartArray[j]);
 				for (k=0;k<cols.length;k++)  
				{
					 if (String(cols[k].dataField).indexOf(name2 +"_") != -1)
					 {
					 	 var column2:FooterAdvancedDataGridColumn = dg_corp.columns[k];
					 	 column2.visible = false;
					 }  
				} 
			}			
		
		}	
  				    
	} 			
	

  	private function onProductosChangeNac(e:Event):void
	{
	    trace(" ____"+  this.name + " -->  onProductosChangeNac.");

	    cwDataGridNac.unwatch();
	    //asign array for countries and visibility
	    if ((prodNacData)  && (paisesNacArr.length >0))
	    {
	    	trace("asignando arreglos por pais....");
	    
	    	for (var j:int=0;j<paisesNacArr.length;j++) 
	    	{
	    		var prefix:String = paisesNacArr[j];
	    		if (prefix == "CL")
	    		{
	    			prodNacCLData = prodNacData[j];
	    		} else if (prefix == "CO")
	    		{
	    			prodNacCOData = prodNacData[j];
	    		} else if (prefix == "PE")
	    		{
	    			prodNacPEData = prodNacData[j];
	    		}else if (prefix == "AR")
	    		{
	    			prodNacARData = prodNacData[j];
	    		} 
	    	} 
	    	
	    }				
		
		// hide countries compra individual
		if ((paisesNacArr)  && (paisesNacArr.length>0) )
		{
			
			//obtener pais
			var hidePaises:Array = new Array();
			hidePaises = new Array("CL","CO","PE","AR"); 
			for (j=0;j<paisesNacArr.length;j++) 
			{
				var cod:String;
				cod = paisesNacArr[j];
				for (var k:int=0;k<paisesPartArray.length;k++)
				{
					if (paisesPartArray[k] == cod)
						hidePaises.splice(k,1);
				}
			}
			trace("hide nac " +  hidePaises);
			
			for (k=0;k<hidePaises.length;k++) 
			{
	    		var prefijo:String = hidePaises[k];
	    		if (prefijo == "CL")
	    		{
	    			vboxCL.visible=false;
	    			vboxCL.height=5;
	    		} else if (prefijo == "CO")
	    		{
	    			vboxCO.visible=false;
	    			vboxCO.height=5;
	    		} else if (prefijo == "PE")
	    		{
	    			vboxPE.visible=false;
	    			vboxPE.height=5;
	    		} else if (prefijo == "AR")
	    		{
	    			vboxAR.visible=false;
	    			vboxAR.height=5;
	    		}
	    									
			}
		}
	
		
		if (existePedido == "1")  
		{
			btnEnviar.enabled = false;
			btnGuardar.enabled = false;
		}							
  				    
	}		


	
/*
	private function modificaTotalesConj(event:AdvancedDataGridEvent):void
	{
		 trace(" ____"+  this.name + " -->  modificaTotalesConj.");
		
		var cantidad:Number = NumericStepper(event.currentTarget.itemEditorInstance).value;
		var prefix:String   = dg_corp.columns[event.columnIndex].dataField;
		var subPrice:Number = 0;
		var subKgs:Number   = 0;
		var subCbm:Number   = 0;
		var total:Number    = 0;				
		
		prefix = prefix.substr(0,3);
		trace("prefijo : " + prefix); 
		subPrice = Number(prodCorpData[event.rowIndex]["unit_price"]);
		subKgs   = Number(prodCorpData[event.rowIndex]["unit_kgs"]);
		subCbm   = Number(prodCorpData[event.rowIndex]["unit_cbm"]);
		 
		 
		if (prefix == "sub")
		{
			
			//update totales all countries
			for (var j:int=0;j<paisesArr.length;j++) 
			{
				prefix = UtilString.toLowerCase(paisesArr[j]);
				if (!isNaN(prodCorpData[event.rowIndex][prefix + "_quantity"]))
				{
					cantidad =  Number(prodCorpData[event.rowIndex][prefix + "_quantity"]);
					
 					prodCorpData[event.rowIndex][prefix + "_sub_price"] = (cantidad==0)? "0": Number(cantidad * subPrice).toFixed(2);
					prodCorpData[event.rowIndex][prefix + "_sub_kgs"]   = (cantidad==0)? "0": Number(cantidad * subKgs).toFixed(2);
					prodCorpData[event.rowIndex][prefix + "_sub_cbm"]   = (cantidad==0)? "0": Number(cantidad * subCbm).toFixed(2);
					
					checkRequiereCorreccion(UtilString.toUpperCase(prefix), cantidad, event.rowIndex);							
					
				}
			}					
			
			
		} 
		else
		{ 
			//update subs
 			prodCorpData[event.rowIndex][prefix + "sub_price"] = (cantidad==0)? "0": Number(cantidad * subPrice).toFixed(2);
			prodCorpData[event.rowIndex][prefix + "sub_kgs"]   = (cantidad==0)? "0": Number(cantidad * subKgs).toFixed(2);
			prodCorpData[event.rowIndex][prefix + "sub_cbm"]   = (cantidad==0)? "0": Number(cantidad * subCbm).toFixed(2);
			
			//sum all countries
			for (var t:int=0;t<paisesArr.length;t++) 
			{
				prefix = UtilString.toLowerCase(paisesArr[t]);
				if (!isNaN(prodCorpData[event.rowIndex][prefix + "_quantity"]))
				{
					total +=  Number(prodCorpData[event.rowIndex][prefix + "_quantity"]);
				}
			}
			
			prodCorpData[event.rowIndex]["sub_quantity"] = (Number(total*100)/100);
			prodCorpData[event.rowIndex]["sub_total"] = (Number(total*subPrice*100)/100);
		}	
		 
	}
	*/
	
	private function validaCantidadCorp(event:AdvancedDataGridEvent):void
	{
		var columnName:String = event.dataField;
		var newValor:Number = 0;
		var oriValor:Number = 0;
		var newPrecio:Number = 0;
		var oriPrecio:Number = 0; 
		var max:Number = 0;
		var msg:String = "";
		var selected:String = "";					 
		
		if (columnName == "vquantity")
		{
			newValor  = NumericStepper(event.currentTarget.itemEditorInstance).value;
			oriValor  = Number(event.currentTarget.editedItemRenderer.data["original_vquantity"]); 

			max = NumericStepper(event.currentTarget.itemEditorInstance).maximum;
			if (newValor == max)
			{
				AdvancedDataGrid(event.currentTarget).destroyItemEditor();
				event.preventDefault();	
				alert.warning("Valor ingresado es igual o superior al máximo permitido ("+  pesosFmt.format(max) +").");
			}
			else
			{
				//cuando la cantidad dada por el proveedor es mayor a la original,
				//se le exige seleccionar un problema del listado
				selected = event.currentTarget.editedItemRenderer.data["vproblem"];      
				if ( (newValor > oriValor) && UtilString.isBlank(selected)) 
				{
					AdvancedDataGrid(event.currentTarget).destroyItemEditor();
					event.preventDefault();
					alert.info("Para ingresar una cantidad mayor, debe seleccionar un problema.");
				}
				
			}	
			
		}
				
		if (columnName == "vprice")
		{
			newPrecio =  NumericStepper(event.currentTarget.itemEditorInstance).value;
			oriPrecio =  Number(event.currentTarget.editedItemRenderer.data["original_vprice"]);
			
			max = NumericStepper(event.currentTarget.itemEditorInstance).maximum;
			if (newPrecio == max)
			{
				AdvancedDataGrid(event.currentTarget).destroyItemEditor();
				event.preventDefault();	
				alert.warning("Precio ingresado es igual o superior al máximo permitido ("+  pesosFmt.format(max) +").");
			}
			else
			{
				//cuando el precio dado por el proveedor es mayor al original,
				//se le exige seleccionar un problema del listado
				selected = event.currentTarget.editedItemRenderer.data["vproblem"];      
				if ( (newPrecio > oriPrecio) && UtilString.isBlank(selected)) 
				{
					AdvancedDataGrid(event.currentTarget).destroyItemEditor();
					event.preventDefault();
													
					alert.info("Para ingresar un precio mayor, debe seleccionar un problema.");
				}
			}	
		}
				
				
		if (columnName == "vproblem")
		{
			newPrecio =  Number(event.currentTarget.editedItemRenderer.data["vprice"]);
			oriPrecio =  Number(event.currentTarget.editedItemRenderer.data["original_vprice"]);

			newValor = Number(event.currentTarget.editedItemRenderer.data["vquantity"]);
			oriValor = Number(event.currentTarget.editedItemRenderer.data["original_vquantity"]); 

			selected = event.currentTarget.editedItemRenderer.data["vproblem"];
			if ( ( (newPrecio > oriPrecio) || (newValor > oriValor)) && UtilString.isBlank(selected) ) 
			{
				//cuando el precio dado por el proveedor es mayor al original,
				event.preventDefault();
				AdvancedDataGrid(event.currentTarget).destroyItemEditor();
				alert.info("No es posible eliminar el problema, ya que existen diferencias en precio o cantidad.");
			} else {
			
				//borrar nota
				event.currentTarget.editedItemRenderer.data["note"] =  ""; 
			}
		}
		
		
		if (columnName == "note")
		{
			msg = TextInput(event.currentTarget.itemEditorInstance).text;
			selected = event.currentTarget.editedItemRenderer.data["vproblem"];
			if ( UtilString.isNotBlank(msg)  && UtilString.isBlank(selected) ) 
			{
				event.preventDefault();
				AdvancedDataGrid(event.currentTarget).destroyItemEditor();
				alert.info("Para ingresar una nota, debe haber indicado previamente un problema.");
			}
		}		
			

	}		
			
			
/*
	private function validaCantidad(event:AdvancedDataGridEvent):void
	{
		var newValor:Number = NumericStepper(event.currentTarget.itemEditorInstance).value;
		var oldValor:Number = event.currentTarget.editedItemRenderer.data[event.dataField];
		var caseName:String = event.dataField;
		var prefix:String = caseName.substr(0,3);
		var pais:String = UtilString.toUpperCase(prefix.substr(0,2));
		var prefijo_pais:String = "";
		var casePack:Number = 0; 
		var resto:Number = 0;
		var row:Number = 0; 
		var qty:Number = 0;
		var subQty:Number = 0;
		var newQty:Number = 0;
		var sumVendor:Number = 0;
		var proposed:Boolean= false;
		var unitPrice:Number = 0;				
		
		
        if ( (newValor == oldValor)  || (event.reason == DataGridEventReason.CANCELLED)) {
            return; 
        }
        
		if (oldValor != -1)
		{

			subQty =  oldValor;
			if ( prefix == "sub" )
			{
				//distribuir diferencia
				trace("editando Sub Quantity ...");
				if ( (paisesArr) && (paisesArr.length) && (subQty > 0) ) {

						//calculo mayor  y menor
						for (var k:int=0; k < paisesArr.length;k++)
						{
							qty = 0;
							casePack = 0;
							resto = 0;
							newQty = 0;
							
							prefijo_pais = UtilString.toLowerCase(paisesArr[k]) + "_";
							casePack = Number(prodCorpData[event.rowIndex][prefijo_pais + "case_pack"]);
							qty =  Number(prodCorpData[event.rowIndex][prefijo_pais + "quantity"]);
						
							if ( (qty) && paisesArr[k] == "CL"){
								
								newQty = Math.round( (newValor* ((qty*100/subQty)/100)) );
								resto = newQty%casePack;
								if ( resto != 0)
								{
									proposed= true;
									newQty = Math.ceil(newQty/casePack)*casePack;
								}
								sumVendor += (newQty);
								prodCorpData[event.rowIndex]["cl_quantity"] = (newQty);
							
				    		} else if ( (qty) && paisesArr[k]  == "CO"){
	
								newQty =  Math.round( (newValor* ((qty*100/subQty)/100)) );
								resto = newQty%casePack;
								if ( resto != 0)
								{
									proposed= true;
									newQty = Math.ceil(newQty/casePack)*casePack;
								}
								sumVendor += (newQty);
								prodCorpData[event.rowIndex]["co_quantity"] = ( newQty);			    			
				    			
				    		} else if ((qty) && paisesArr[k]  == "PE"){
								newQty =  Math.round( (newValor* ((qty*100/subQty)/100)) );
								resto = newQty%casePack;
								if ( resto != 0)
								{
									proposed= true;
									newQty = Math.ceil(newQty/casePack)*casePack;
								}
								sumVendor += (newQty);
								prodCorpData[event.rowIndex]["pe_quantity"] = (newQty);			    			
				    			
				    		} else if ((qty) && paisesArr[k]  == "AR"){
								newQty =  Math.round( (newValor* ((qty*100/subQty)/100)) );
								resto = newQty%casePack;
								if ( resto != 0)
								{
									proposed= true;
									newQty = Math.ceil(newQty/casePack)*casePack;
								}
								sumVendor += (newQty);
								prodCorpData[event.rowIndex]["ar_quantity"] = ( newQty);		    			
				    			
				    		}
				    		
						}
					
						
					
					//update col sub_total = qty * unit_price
					unitPrice = Number(prodCorpData[event.rowIndex]["unit_price"]);
					prodCorpData[event.rowIndex]["sub_total"]  = Number(sumVendor * unitPrice);
					
					NumericStepper(event.currentTarget.itemEditorInstance).value = sumVendor;
					event.currentTarget.editedItemRenderer.data[event.dataField] = -1;
					if (proposed)
					{
						alert.info("Se propone una cantidad superior a la ingresada, la cual ha sido distribuída entre los países participantes.");
					} else {
						alert.info("La cantidad ingresada ha sido distribuída entre los países participantes.");
					}
												

				} else if (subQty  == 0)
				{
					sumVendor = newValor;
					prodCorpData[event.rowIndex][ UtilString.toLowerCase(paisesArr[0]) + "_quantity"]  = newValor;					
					
					//update col sub_total = qty * unit_price
					unitPrice = Number(prodCorpData[event.rowIndex]["unit_price"]);
					prodCorpData[event.rowIndex]["sub_total"]  = Number(sumVendor * unitPrice);
					
					event.currentTarget.editedItemRenderer.data[event.dataField] = -1;						
				
				}					
				

			} 
			else
			{
			
				//define case-pack related
				caseName = prefix + "case_pack";
				casePack = Number(prodCorpData[event.rowIndex][caseName]);
				

				if ( isNaN(casePack) || (casePack ==0)) 
				{
					AdvancedDataGrid(event.currentTarget).destroyItemEditor();
					event.preventDefault();
					alert.error("Case Pack no válido, no es posible validar cantidad  ingresada.");
				} 
				else 
				{
					
					var max:Number = NumericStepper(event.currentTarget.itemEditorInstance).maximum;
					if (newValor == max)
					{
						AdvancedDataGrid(event.currentTarget).destroyItemEditor();
						event.preventDefault();								
						alert.warning("Valor ingresado es igual o superior al máximo permitido ("+ pesosFmt.format(max) +").");
					}
					else
					{						
					
						resto=newValor%casePack;
						if (resto !=0)
						{
							newValor = 	Math.ceil(newValor/casePack)*casePack;
							NumericStepper(event.currentTarget.itemEditorInstance).value = 	newValor;
							event.currentTarget.editedItemRenderer.data[event.dataField] = -1;			
							alert.warning("La cantidad ingresada debe ser múltiplo del case pack ("+ casePack + ").  Se propone una cantidad superior válida.");
						}
						
						//siempre validar si requiere correcion 
						checkRequiereCorreccion(pais, newValor, event.rowIndex);

// 2010-01-28 - Modificado por RGA  (Corrige problema al chequear correción)
//						else 
//						{
//							
//							//si cambio es mayor que la tolerancia, habilitar label "Requiere Correccion"
//							checkRequiereCorreccion(pais, newValor, event.rowIndex);
//
//						}
					}	
				}
			}
			
		}
	}


    private function checkRequiereCorreccion(pais:String, newValor:Number, row:Number):void 
    {
		var valorTol:Number = 0;
		var valorQty:Number = 0;
		var prefix:String = UtilString.toLowerCase(pais) + "_";
		var encendido:Boolean = false;
		
		valorTol = prodCorpData[row][prefix + "max_tolerancia"];
		
		if (newValor > valorTol)						
		{
				if (pais == "CL")
				{
					cl_group.headerText = "on";
				}
				else if (pais == "CO")
				{
					co_group.headerText = "on";
				}						
				else if (pais == "PE")
				{
					pe_group.headerText = "on";
				}
				else if (pais == "AR")
				{
					ar_group.headerText = "on";
				}
			
			//inserta en arreglo	
			if (paisesCorreccion.indexOf(pais) < 0)
			{
				paisesCorreccion.push(pais);
			}
			
			//(cambio RG 19.10.2009)  
			//En caso mostrar "Requiere Confirmación" se debe bloquear boton guardar 
			btnGuardar.enabled = false;						
			
        }
        else
        {
			//verifico si corresponde mantener encendido label
			encendido = false;		        
        	for (var j:int=0;j<prodCorpData.length;j++) 
			{
				if (j != row)
				{
					valorTol = isNaN(prodCorpData[j][prefix + "max_tolerancia"])? 0: Number(prodCorpData[j][prefix + "max_tolerancia"]);
					valorQty = isNaN(prodCorpData[j][prefix + "quantity"])? 0: Number(prodCorpData[j][prefix + "quantity"]);
					
					if (valorQty > valorTol)
					{
						encendido = true;
						break;
					}
				} 
			}
			
			if (!encendido)
			{
				if (pais == "CL")
				{
					cl_group.headerText = "off";
				}
				else if (pais == "CO")
				{
					co_group.headerText = "off";
				}						
				else if (pais == "PE")
				{
					pe_group.headerText = "off";
				}
				else if (pais == "AR")
				{
					ar_group.headerText = "off";
				}

				
				//remove form array	
				for (var k:int=0;k<paisesCorreccion.length;k++)
				{
					if (paisesCorreccion[k] == pais)
						paisesCorreccion.splice(k,1);
				}							
					
			} 		        
        
    	}
    	
    	if (paisesCorreccion.length == 0)
    	{
    		btnGuardar.enabled = true;
    	}
    }
*/
	
	private function dataTipNombre(value:Object):String{
		return (value.toString());
	}	
			
	
    private function onCreationCompleteDGCorp():void 
    {
		var col:AdvancedDataGridColumn;
        var cols:Array = dg_corp.columns;
		
		numericStepperFac = new ClassFactory(NumericStepper);
        numericStepperFac.properties = {minimum:0, maximum:999999999, maxChars:9};
        
        numericStepperPrice = new ClassFactory(NumericStepper);
        numericStepperPrice.properties = {minimum:0.00, maximum:999999999.00, 
        								  maxChars:9, stepSize:0.01};	        
        
		myDropdownFactory = new ClassFactory(List);
		myDropdownFactory.properties = {showDataTips:true, dataTipFunction:dataTipNombre}		        
        
		comboFactory = new ClassFactory(ComboBox);
		comboFactory.properties = {dataProvider:problems, dropdownFactory:myDropdownFactory};  
		
		textInputFactory = new ClassFactory(TextInput);
		textInputFactory.properties = {maxChars:100};  	
        
		trace("____"+  this.name + " -->  onCreationCompleteDGCorp.");
        
        var i:int =0;    
        while (i < cols.length)
        {
            	//para todas las columnas
            	col= cols[i];
            	col.editable = false;
					            	
				//format
				if ( (i==6) ||(i==8) || ((i>=14) && (i<=16)) || ((i>=22) && (i<=24)) || ((i>=30) && (i<=32)) || ((i>=38) && (i<=40)) ) 
				{
					var sf_c8:ClassFactory = new ClassFactory(ScreenFormat);
					sf_c8.properties = {fieldName:  col.dataField}
					col.itemRenderer = sf_c8; 
				}
				
				//renderiza NumericStepper vendorQuantity 
				if ( i==41 ) 
				{
					col.editable = true;
					col.editorDataField = "value";
					col.itemEditor = numericStepperFac;
				}            	

				//renderiza NumericStepper vendorPrice
				if ( i==42 )
				{
					col.editable = true;
					col.editorDataField = "value";
					col.itemEditor = numericStepperPrice;
				}  
				
				//renderiza combo Problemas
	        	if (i==43)
	        	{
	            	col.editable = true;
	            	col.editorDataField = "value";
	            	col.itemEditor = comboFactory;            		
	        	}
	        	
	        	//renderiza Note
	        	if (i==44)
	        	{
	            	col.editable = true;
	            	col.itemEditor = textInputFactory;
	        	}            	
            	          	
            	i++;
        }
        
     }
     
 /*   
	private function modificaTotalesNac(event:AdvancedDataGridEvent, paisArr:ArrayCollection):void
	{
		var cantidad:Number =  paisArr.getItemAt(event.rowIndex).paisQuantity;
		var subPrice:Number = 0;
		var subKgs:Number   = 0;
		var subCbm:Number   = 0;
		var total:Number    = 0;
		
		subPrice = Number(paisArr[event.rowIndex]["unitPrice"]);
		subKgs   = Number(paisArr[event.rowIndex]["unitKgs"]);
		subCbm   = Number(paisArr[event.rowIndex]["unitCbm"]);

		// Get the name of the column being editted.
		paisArr.getItemAt(event.rowIndex).subPrice = (cantidad==0)? "0": Number(cantidad * subPrice).toFixed(2);
		paisArr.getItemAt(event.rowIndex).subKgs =   (cantidad==0)? "0": Number(cantidad * subKgs).toFixed(2);
		paisArr.getItemAt(event.rowIndex).subCbm =   (cantidad==0)? "0": Number(cantidad * subCbm).toFixed(2);
		
	} 	         
*/


	private function validaCantidadNac(event:AdvancedDataGridEvent):void
	{
	
		var columnName:String = event.dataField;
		var oldValor:Number = 0;
		var newValor:Number = 0;
		var oriValor:Number = 0;
		var newPrecio:Number = 0;
		var oriPrecio:Number = 0; 
		var casePack:Number = 0;
		var resto:Number = 0;	
		var propuesto:Number = 0;
		var max:Number = 0;
		var selected:String = "";
		
		var dataOk:Boolean = true;
		var preventEdit:Boolean = true;		
		var msg:String = "";
	
		if (columnName == "vquantity")
		{
			oldValor = event.currentTarget.editedItemRenderer.data[event.dataField];	
			if (oldValor == -1){
				return;
			}
			
			oriValor = Number(event.currentTarget.editedItemRenderer.data["original_vquantity"]); 
			newValor = NumericStepper(event.currentTarget.itemEditorInstance).value;
			casePack = Number(event.currentTarget.editedItemRenderer.data["casePack"]); 
			max = NumericStepper(event.currentTarget.itemEditorInstance).maximum;	
			
			if ( isNaN(casePack) || (casePack ==0)) 
			{
				dataOk = false;
				msg = "Case Pack no válido, no es posible validar cantidad ingresada.";
			} 
			else 
			{
				if (newValor >= max)
				{
					dataOk = false;
					msg = "Valor ingresado es igual al máximo permitido ("+ pesosFmt.format(max) +").";
				}
				else
				{					
					resto=newValor%casePack;
					if (resto == 0) {
						propuesto = newValor;
					} else {
						propuesto = Math.ceil(newValor/casePack)*casePack;
					}

					//cuando la cantidad dada por el proveedor es mayor a la original,
					//se le exige seleccionar un problema del listado
					selected = event.currentTarget.editedItemRenderer.data["vproblem"];						
					if ( (propuesto > oriValor) && UtilString.isBlank(selected)) {
						dataOk = false;
						msg = "Para ingresar una cantidad mayor, debe indicar previamente un problema.";
					
					} else {
						
						if (resto != 0) {
							NumericStepper(event.currentTarget.itemEditorInstance).value = propuesto;
							event.currentTarget.editedItemRenderer.data[event.dataField] = -1;  						
							dataOk = false;
							preventEdit = false;
							msg = "La cantidad ingresada debe ser múltiplo del case pack ("+ casePack + ") del producto. Se propone una cantidad válida.";
						}
					}	
				}	
			}
			
			if (!dataOk)
			{
				if (preventEdit){
					event.preventDefault();
					AdvancedDataGrid(event.currentTarget).destroyItemEditor();
				}
				alert.info(msg);			
			}	
						
		}	
		
		
		if (columnName == "vprice")
		{
			newPrecio =  NumericStepper(event.currentTarget.itemEditorInstance).value;
			oriPrecio =  Number(event.currentTarget.editedItemRenderer.data["original_vprice"]);
			max = NumericStepper(event.currentTarget.itemEditorInstance).maximum;
			
			if (newPrecio == max)
			{
				dataOk = false;
				msg = "Precio ingresado es igual o superior al máximo permitido ("+  pesosFmt.format(max) +").";
			}
			else
			{
				//cuando el precio dado por el proveedor es mayor al original,
				//se le exige seleccionar un problema del listado
				selected = event.currentTarget.editedItemRenderer.data["vproblem"];      
				if ( (newPrecio > oriPrecio) && UtilString.isBlank(selected)) 
				{
					dataOk = false;
					msg = "Para ingresar un precio mayor, debe seleccionar un problema.";
				}
			}
			
			if (!dataOk)
			{
				event.preventDefault();
				AdvancedDataGrid(event.currentTarget).destroyItemEditor();
				alert.info(msg);			
			}				
			
		}			
			
		if (columnName == "vproblem")
		{
			newPrecio =  Number(event.currentTarget.editedItemRenderer.data["vprice"]);
			oriPrecio =  Number(event.currentTarget.editedItemRenderer.data["original_vprice"]);

			newValor = Number(event.currentTarget.editedItemRenderer.data["vquantity"]);
			oriValor = Number(event.currentTarget.editedItemRenderer.data["original_vquantity"]); 

			selected = event.currentTarget.editedItemRenderer.data["vproblem"];
			if ( ( (newPrecio > oriPrecio) || (newValor > oriValor)) && UtilString.isBlank(selected) ) 
			{
				//cuando el precio dado por el proveedor es mayor al original,
				event.preventDefault();
				AdvancedDataGrid(event.currentTarget).destroyItemEditor();
				alert.info("No es posible eliminar el problema, ya que existen diferencias en precio o cantidad.");
			} else {
			
				//borrar nota
				event.currentTarget.editedItemRenderer.data["note"] =  ""; 
			}
		}
		
		
		if (columnName == "note")
		{
			
			msg = TextInput(event.currentTarget.itemEditorInstance).text;
			selected = event.currentTarget.editedItemRenderer.data["vproblem"];
			if ( UtilString.isNotBlank(msg)  && UtilString.isBlank(selected) ) 
			{
				event.preventDefault();
				AdvancedDataGrid(event.currentTarget).destroyItemEditor();
				alert.info("Para ingresar una nota, debe haber indicado previamente un problema.");
			}
		}		
			
			
	}




 	private function onCreationCompleteDGNac(adg:AdvancedDataGrid):void {
		var i:int = 0;
		var col:AdvancedDataGridColumn;
		var cols:Array = adg.columns;
		var anchoCols:Array = new Array(.04,.02,.1 ,.02,.06,.06,
										.06,.04,.06,.06,.06,.06,
										.08,.08,.1,.1 );
		
		trace("____"+  this.name + " -->  onCreationCompleteDGNac");
		
		numericStepperFac = new ClassFactory(NumericStepper);
		numericStepperFac.properties = {minimum:0, maximum:999999999, maxChars:9};
			
        numericStepperPrice = new ClassFactory(NumericStepper);
        numericStepperPrice.properties = {minimum:0.00, maximum:999999999.00, 
        								  maxChars:9, stepSize:0.01};			
			
		myDropdownFactory = new ClassFactory(List);
		myDropdownFactory.properties = {showDataTips:true, dataTipFunction:dataTipNombre}		        
        
		comboFactory = new ClassFactory(ComboBox);
		comboFactory.properties = {dataProvider:problems, dropdownFactory:myDropdownFactory};  			

		textInputFactory = new ClassFactory(TextInput);
		textInputFactory.properties = {maxChars:100};  			
		
		
		screenFormat = new ClassFactory(ScreenFormat);	
			
		while (i < cols.length)
		{
			//para todos
			col= cols[i];
			col.editable = false;
			col.width = Math.round(adg.width*anchoCols[i]);

			//renderiza NumericStepper vendorQuantity 
			if ( i==12)
			{
				col.editable = true;
				col.editorDataField = "value";
				col.itemEditor = numericStepperFac;
			}
			
			//renderiza NumericStepper vendorPrice
			if ( i==13 )
			{
				col.editable = true;
				col.editorDataField = "value";
				col.itemEditor = numericStepperPrice;
			}			
			
			
			//renderiza format
			if  ( (i==6) || (i==9) ||(i==10) ||(i==11) ) 
			{
				screenFormat.properties = {fieldName: col.dataField}
				col.itemRenderer = screenFormat; 
			}	
			
			//renderiza combo Problemas
        	if (i==14)
        	{
            	col.editable = true;
            	col.editorDataField = "value";
            	col.itemEditor = comboFactory;            		
        	}
        	
        	//renderiza Note
        	if (i==15)
        	{
            	col.editable = true;
            	col.itemEditor = textInputFactory;
        	}

			i++;
		}

	} 


     
    public function textFunction(col:AdvancedDataGridColumn):String
	{
		var txt:String = "";
		if ((col.headerText =="Case Pack") || (col.headerText =="CP"))
		{
			txt="Total";
		}
		return txt;
	}
	
	
	public function sumFunctionCorp(col:AdvancedDataGridColumn):String
	{
		var sum:Number = 0;
		if (prodCorpData != null)
		{
			for (var i:int = 0; i < prodCorpData.length; i++)
			{
				if (!isNaN(prodCorpData[i][col.dataField]))
				{
					sum += Number(prodCorpData[i][col.dataField]);
				}
			}
		}
		return  pesosFmt.format((Number(sum*100)/100));
	}
	
	public function sumFunctionNacCL(col:AdvancedDataGridColumn):String
	{
		var sum:Number = 0;
		if (prodNacCLData != null)
		{
			for (var i:int = 0; i < prodNacCLData.length; i++)
			{
				if (!isNaN(prodNacCLData[i][col.dataField]))
				{
					sum += Number(prodNacCLData[i][col.dataField]);
				}
			}
		}
		return  pesosFmt.format((Number(sum*100)/100));
	}
	
	public function sumFunctionNacCO(col:AdvancedDataGridColumn):String
	{
		var sum:Number = 0;
		if (prodNacCOData != null)
		{
			for (var i:int = 0; i < prodNacCOData.length; i++)
			{
				if (!isNaN(prodNacCOData[i][col.dataField]))
				{
					sum += Number(prodNacCOData[i][col.dataField]);
				}
			}
		}
		return  pesosFmt.format((Number(sum*100)/100));
	}
	
	public function sumFunctionNacPE(col:AdvancedDataGridColumn):String
	{
		var sum:Number = 0;
		if (prodNacPEData != null)
		{
			for (var i:int = 0; i < prodNacPEData.length; i++)
			{
				if (!isNaN(prodNacPEData[i][col.dataField]))
				{
					sum += Number(prodNacPEData[i][col.dataField]);
				}
			}
		}
		return  pesosFmt.format((Number(sum*100)/100));
	}
	
	public function sumFunctionNacAR(col:AdvancedDataGridColumn):String
	{
		var sum:Number = 0;
		if (prodNacARData != null)
		{
			for (var i:int = 0; i < prodNacARData.length; i++)
			{
				if (!isNaN(prodNacARData[i][col.dataField]))
				{
					sum += Number(prodNacARData[i][col.dataField]);
				}
			}
		}
		return  pesosFmt.format((Number(sum*100)/100));
	}
	
	
	
	//styleFunction="setColorStyle" (for ADG)
     public function setColorSubQuantity(data:Object, col:AdvancedDataGridColumn):Object
     {
         if(data["subQuantity"] <= 0)
             return {color:0xFF0000};
         else    
 			return {color:0x0000FF};
 
         return null;
     }  		

     public function setColorPaisQuantity(data:Object, col:AdvancedDataGridColumn):Object
     {
         if(data["paisQuantity"] <= 0)
             return {color:0xFF0000};
         else    
 			return {color:0x0000FF};
 
         return null;
     } 	
     

    public function setColorStyle(data:Object, col:AdvancedDataGridColumn):Object
    {
         if ((data["vquantity"] <= 0) || (data["vprice"] <= 0))
             return {color:0xFF0000};
         else    
 			return {color:0x0000FF};
 
         return null;
     } 

	private function rescueProblemaId(problemName:String):String 
	{
		var result:String="";
		
		if (problemaArr.length>0)
		{
			for(var i:int=0; i< problemaArr.length; i++)
			{
				if ( UtilString.equalsIgnoreCase(problemaArr[i]["desc"],problemName))
				{
					result = problemaArr[i]["id"];
					break;
				}
			}
		}
		return result;
		
	}	


	private function getProductosModificados():void
	{
		//var productos:ArrayCollection = prodPicArr; 
		var newValor:Number = 0;
		var oriValor:Number = 0;
		var newPrecio:Number = 0;
		var oriPrecio:Number = 0; 
		var problema:String = "";		
		var i:Number = 0;  


		//get productos corp updated
		for (var t:int = 0; t < prodCorpData.length; t++)
		{
			newValor  = prodCorpData[t]["vquantity"];
			oriValor  = prodCorpData[t]["original_vquantity"];
			newPrecio = prodCorpData[t]["vprice"];
			oriPrecio = prodCorpData[t]["original_vprice"];
			problema  = prodCorpData[t]["vproblem"];	
			
			
			if ( (newValor != oriValor) || (newPrecio != oriPrecio) 
							 			||  !UtilString.isBlank(problema) )
			{
				
				var objProd:Object = new Object();
	    		//objProd.pais = productos[i]["pais"];
				objProd.vin = prodCorpData[t]["vin"];
			//	objProd.sku = prodCorpData[t]["sku"];
	    		objProd.vprice = newPrecio;
	    		objProd.vquantity = newValor;
	    		objProd.problemId = rescueProblemaId(problema); 
	    		objProd.note = prodCorpData[t]["note"];
	    		
				prodUpdated.addItem(objProd);				
				
	  		}
	  		
		}
	
		//get prod individuales modificados

		//get productos CL
		for (i=0; i < prodNacCLData.length; i++)
		{
			newValor  = prodNacCLData[i]["vquantity"];
			oriValor  = prodNacCLData[i]["original_vquantity"];
			newPrecio = prodNacCLData[i]["vprice"];
			oriPrecio = prodNacCLData[i]["original_vprice"];
			problema  = prodNacCLData[i]["vproblem"];	
								
			if ( (newValor != oriValor) || (newPrecio != oriPrecio) 
							 			||  !UtilString.isBlank(problema) )
			{
				var obj:Object = new Object();
				obj.pais = "CL";
			//	obj.vin = prodNacCLData[i]["vin"];
				obj.sku = prodNacCLData[i]["sku"];
	    		obj.vprice = newPrecio;  
	    		obj.vquantity = newValor;
	    		obj.problemId = rescueProblemaId(problema);
	    		obj.note = prodNacCLData[i]["note"]; 
	    		
	    		prodUpdated.addItem(obj);	
	    		
			}
		}				
		
		//get productos CO
		for (i=0; i < prodNacCOData.length; i++)
		{
			newValor  = prodNacCOData[i]["vquantity"];
			oriValor  = prodNacCOData[i]["original_vquantity"];
			newPrecio = prodNacCOData[i]["vprice"];
			oriPrecio = prodNacCOData[i]["original_vprice"];
			problema  = prodNacCOData[i]["vproblem"];	
								
			if ( (newValor != oriValor) || (newPrecio != oriPrecio) 
							 			||  !UtilString.isBlank(problema) )
			{
				var objCO:Object = new Object();
				objCO.pais = "CO";
		//		objCO.vin = prodNacCOData[i]["vin"];
				objCO.sku = prodNacCOData[i]["sku"];
	    		objCO.vprice = newPrecio;  
	    		objCO.vquantity = newValor;
	    		objCO.problemId = rescueProblemaId(problema);
	    		objCO.note = prodNacCOData[i]["note"]; 
	    		
	    		prodUpdated.addItem(objCO);	
	    		
			}
		}			
		
		
		//get productos PE
		for (i=0; i < prodNacPEData.length; i++)
		{
			newValor  = prodNacPEData[i]["vquantity"];
			oriValor  = prodNacPEData[i]["original_vquantity"];
			newPrecio = prodNacPEData[i]["vprice"];
			oriPrecio = prodNacPEData[i]["original_vprice"];
			problema  = prodNacPEData[i]["vproblem"];	
								
			if ( (newValor != oriValor) || (newPrecio != oriPrecio) 
							 			||  !UtilString.isBlank(problema) )
			{
				var objPE:Object = new Object();
				objPE.pais = "PE";
		//		objPE.vin = prodNacPEData[i]["vin"];
				objPE.sku = prodNacPEData[i]["sku"];
	    		objPE.vprice = newPrecio;  
	    		objPE.vquantity = newValor;
	    		objPE.problemId = rescueProblemaId(problema);
	    		objPE.note = prodNacPEData[i]["note"];  
	    		
	    		prodUpdated.addItem(objPE);	
	    		
			}
		}	
	
		//get productos AR
		for (i=0; i < prodNacARData.length; i++)
		{
			newValor  = prodNacARData[i]["vquantity"];
			oriValor  = prodNacARData[i]["original_vquantity"];
			newPrecio = prodNacARData[i]["vprice"];
			oriPrecio = prodNacARData[i]["original_vprice"];
			problema  = prodNacARData[i]["vproblem"];	
								
			if ( (newValor != oriValor) || (newPrecio != oriPrecio) 
							 			||  !UtilString.isBlank(problema) )
			{
				var objAR:Object = new Object();
				objAR.pais = "AR";
		//		objAR.vin = prodNacARData[i]["vin"];
				objAR.sku = prodNacARData[i]["sku"];
	    		objAR.vprice = newPrecio;  
	    		objAR.vquantity = newValor;
	    		objAR.problemId = rescueProblemaId(problema); 
	    		objAR.note = prodNacARData[i]["note"]; 
	    		
	    		prodUpdated.addItem(objAR);	
	    		
			}
		}	
	
	}		
		
/*
		
	private function checkPaisesCorreccionEnviar():void 
	{

		if (paisesCorreccion.length > 0 )
		{

			//show msg paises participantes
			var lista:String = "";
			for (var i:int=0; i<paisesCorreccion.length; i++)
			{
				lista +=  XML(paisesNombres).pais.(@codIata == paisesCorreccion[i]).@nombre + "\n";
			}
			
			alert.info("Se enviará una solicitud de corrección a los siguientes paises:\n" + lista, onClickBtnEnviar);
		} else {
		
			onClickBtnEnviar(new CloseEvent("cerrar"));
		}

		
	}				
*/

	private function onClickBtnEnviar():void
	{
		var savePicEvt:grabarProductosPicEvent = new grabarProductosPicEvent();
		var version:Number = new Number(infoSfpVo.version);
			
		//get cambios
		getProductosModificados();
		
		//no existen condiciones para envío
	 	savePicEvt.idPedidoCorp = pedidoCorpId;
		savePicEvt.version = ((version - Math.floor(version))>0)? Math.ceil(version) + ".0":(version+1) + ".0";
		savePicEvt.idProveedor = infoSfpVo.proveedorId;
		savePicEvt.estado = EstadosBPM.ENVIO;
		savePicEvt.idEmpresa = empresaId;
		savePicEvt.productosPicArr = prodUpdated;  //listado de prod. modificados

			
		savePicEvt.dispatch();
		btnEnviar.enabled = false;
      	btnGuardar.enabled = false;				
			

	}



     
	public function onClickBtnGuardar():void
	{	
		/*
		var savePedidoEvt:grabarPedidoCorpEvent = new grabarPedidoCorpEvent();
		var new_version:Number = new Number(infoSfpVo.version);
		
		//obtener productos modificados
		getProductosModificados();
		
		new_version += Number(0.1);
 		savePedidoEvt.idPedidoCorp = pedidoCorpId;
		savePedidoEvt.idEmpresa = empresaId;
		savePedidoEvt.idProveedor = infoSfpVo.proveedorId;
		savePedidoEvt.estado = EstadosBPM.GUARDA;
		savePedidoEvt.version = new_version.toFixed(1);

		if (prodCorpUpdated.length > 0 ) 
		{
			savePedidoEvt.productosCorpArr = prodCorpUpdated;  //listado de prod. modificados
		}	
		
		if (prodNacUpdated.length > 0 )
		{
			savePedidoEvt.productosNacArr = prodNacUpdated;  //listado de prod. modificados
		}	
		
		savePedidoEvt.dispatch();
		*/
		btnGuardar.enabled = false;	
      	btnEnviar.enabled = false;											
	}
	
	
	
	
        private function generarReporte(formato:String):void 
        {
  
  			alert.info("Reporte no disponible");
            
/*
            var url:String;
            var sourceCorp:String =""; 
            var sourceNac:String = "";
            
            if (dg_corp) {
            	sourceCorp = DataGridExport.exportCSV(dg_corp, "Corporativos");
            }
            if (paisesNacArr) {
            	
            	for (var k:int=0;k<paisesNacArr.length;k++)
				{
		    		var prefijo:String = paisesNacArr[k];
					//trace("pais envio: " + prefijo);
		    		if (prefijo == "CL")
		    		{
		    			sourceNac  += DataGridExport.exportCSV(dg_cl, "CHILE") + "|";
		    		} else if (prefijo == "CO")
		    		{
		    			sourceNac  += DataGridExport.exportCSV(dg_co, "COLOMBIA") + "|";
		    		} else if (prefijo == "PE")
		    		{
		    			sourceNac  += DataGridExport.exportCSV(dg_pe, "PERU") + "|";
		    		} else if (prefijo == "AR")
		    		{
		    			sourceNac  += DataGridExport.exportCSV(dg_ar, "ARGENTINA") + "|";
		    		}
				}

            		
            }
            
            //remove last separator
            if (sourceNac.charAt(sourceNac.length-1) == '|')
            {
            	sourceNac = sourceNac.substring(0, sourceNac.length-1);
            }	
			
			//send data for report
			UploadPostHelper.uploadDataReport( 'ig7.txt', uploadDataURL, sourceCorp);
			UploadPostHelper.uploadDataReport( 'sub_ig7.txt', uploadDataURL, sourceNac);

			
		    //call report					
            var request:URLRequest = new URLRequest();
			request.url = reporteURL + "?formato="+ formato +
						"&fileName=ig7.txt"+
						"&pNumeroSFP="+ infoSfpVo.numeroSFP +
						"&pEstado="+ infoSfpVo.estado + 
						"&pFecha="+ infoSfpVo.fecha_formato +
						"&pProveedor="+ infoSfpVo.proveedorNombre + " ( " + infoSfpVo.proveedorId + " )" +
						"&pVersion="+ infoSfpVo.version +
						"&pIntMerchant="+ infoSfpVo.merchantNombre;
			request.method = URLRequestMethod.POST;
			//request.data = variables;
            navigateToURL(request, '_blank');						
*/			

			
        }						
  			